<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { showLoadingToast, closeToast, showFailToast, showSuccessToast } from "vant";
import usePost from "@/hooks/usePost";
import Upload from "@/components/Upload/index.vue";
import { formInputItem } from "./constants";

const router = useRouter();
const { runAsync: fetchAdd } = usePost("POST", "/mistake-api/api/quote/item/insert");
const formRefs = ref<any>([]);
const errForm = ref<any>({
	itemCodeError: "",
	extraDescError: ""
});
const selectForm = ref<any>({
	itemCode: "", //定价编号
	file: [], //文件
	extraDesc: "" // 定价说明
});
const formList = ref<any>([JSON.parse(JSON.stringify(formInputItem))]);
const onAdd = () => {
	formList.value.push(JSON.parse(JSON.stringify(formInputItem)));
};
const onRemove = (index: number) => {
	formList.value.splice(index, 1);
};
/** 校验表单 */
const validateForms = async () => {
	let formRefValidateRes = true;
	for (const refItem of formRefs.value) {
		try {
			await refItem!.validate();
		} catch (error) {
			formRefValidateRes = false;
		}
	}
	return formRefValidateRes;
};
const onSubmit = async () => {
	let validateRes = true;
	Object.keys(selectForm.value).forEach((key: any) => {
		if (!selectForm.value[key]) {
			errForm.value[key + "Error"] = "请填写";
			validateRes = false;
		} else {
			errForm.value[key + "Error"] = "";
		}
	});

	const formRefValidateRes = await validateForms();
	if (!validateRes) return;
	if (!selectForm.value.file.length) {
		showFailToast("请上传文件!");
		return;
	}
	if (formRefValidateRes) {
		showLoadingToast({
			message: "提交中...",
			duration: 0,
			forbidClick: true
		});
		const detailList = formList.value.map((item: any) => {
			const obj: any = {};
			item.forEach((i: { key: string; value: string }) => {
				obj[i.key] = i.value;
			});
			return obj;
		});
		const params = {
			attachment: selectForm.value.file.map((i: { fileName: any }) => i.fileName).join(","),
			attachmentPath: selectForm.value.file.map((i: { fileUrl: any }) => i.fileUrl).join(","),
			extraDesc: selectForm.value.extraDesc,
			itemCode: selectForm.value.itemCode,
			detailList
		};
		const { ok } = await fetchAdd(params);
		if (ok) {
			closeToast();
			showSuccessToast({
				message: "提交成功",
				onClose: () => {
					router.replace({
						path: "/approveList",
						query: { type: 2, menu: 1 }
					});
				}
			});
		}
	}
};
</script>

<template>
	<div>
		<van-cell-group class="org" inset>
			<van-cell title="定价编号" required class="cell-field">
				<template #label>
					<van-field v-model="selectForm.itemCode" placeholder="请输入定价编号" :error-message="errForm.itemCodeError" />
				</template>
			</van-cell>
		</van-cell-group>
		<div class="content">
			<div class="form-list" v-for="(list, index) in formList" :key="index">
				<div class="title sub-title">
					<span> 明细{{ !index ? "" : ` (${index + 1})` }}</span>
					<van-icon name="delete-o" v-if="formList.length > 1" @click="onRemove(index)" />
				</div>
				<van-form label-align="top" ref="formRefs">
					<van-cell-group inset>
						<van-field
							v-for="item in list"
							:key="item.key"
							v-model="item.value"
							:name="item.key"
							:label="item.label"
							:placeholder="`请输入${item.label}`"
							required
							:rules="[{ required: true, message: `请填写` }]"
						/>
					</van-cell-group>
				</van-form>
			</div>
			<div class="add" @click="onAdd">
				<van-icon name="plus" />
				<div>添加明细</div>
			</div>
			<div class="title sub-title">备注：以下价格均含税13%</div>

			<van-cell-group class="org" inset>
				<!-- 附件部分 -->
				<van-cell center title="附件结果" class="file">
					<template #label>
						<Upload
							ref="attachmentsRef"
							v-model="selectForm.file"
							buttonType
							accept="*"
							:max-count="30"
							:max-size="500 * 1024 * 1024"
						>
						</Upload>
					</template>
				</van-cell>
				<van-cell center title="定价说明" class="file">
					<template #label>
						<van-field
							rows="3"
							type="textarea"
							v-model="selectForm.extraDesc"
							placeholder="请输入定价说明"
							required
							:error-message="errForm.extraDescError"
						/>
					</template>
				</van-cell>
			</van-cell-group>

			<div style="margin: 16px">
				<van-button round block type="primary" @click="onSubmit"> 提交 </van-button>
			</div>
		</div>
	</div>
</template>

<style scoped lang="less">
.org {
	margin-top: 10px;
	margin-bottom: 10px;
}
.sub-title {
	margin: 10px 18px;
	color: #969799;
	font-size: 14px;
}
.content {
	.form-list {
		.title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			.van-icon {
				font-size: 16px;
			}
		}
	}
	.add {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 10px 18px;
	}
}
:deep(.file .van-cell__title) {
	& > span::before {
		content: "* ";
		color: #ee0a24;
	}
}

.cell-field {
	.van-cell__label {
		.van-field {
			padding: 0 !important;
		}
	}
}
</style>
